//
//  OvertimeRLViewController.swift
//  mggz
//
//  Created by QinWei on 2018/4/17.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Moya
import ObjectMapper
import MJRefresh
class OvertimeRLViewController: UIViewController {
    fileprivate var totalPage:Int?
    fileprivate var currentPage = 1
    var projectModel: ProjectModel?//当前项目
    lazy var itemArray : [OvertimePlanModel] = [OvertimePlanModel]()
    lazy var historyArray : [OvertimePlanModel] = [OvertimePlanModel]()
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.getOvertimePlanData()
        self.setupTableView()
        let tableFooter = MJRefreshAutoNormalFooter { [unowned self] in
            self.getNextPage()
        }
        self.tableView.mj_footer = tableFooter
        
        self.getOvertimeHistoryData()
        self.getOvertimeHistoryData()
    }
    fileprivate func setupTableView(){
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(UINib.init(nibName: "OvertimeRecordCell", bundle: nil), forCellReuseIdentifier: "record")
    }
    fileprivate func getOvertimePlanData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
       
        guard let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else{
            return
        }
     LCAPiSubManager.request(.GetOvertimeApplyRecord(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
               
                
                guard  let resultDic : NSArray = jsonString["Result"] as? NSArray else{
                    return
                }
                self.itemArray = Mapper<OvertimePlanModel>().mapArray(JSONObject: resultDic)!
                self.tableView.reloadData()
            }
        }
    }
    
    func getNextPage() {
        guard (self.totalPage != nil) else {
            return
        }
        if self.currentPage >= self.totalPage! {
            self.tableView.mj_footer.endRefreshingWithNoMoreData()
            return
        }
        
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else{
            return
        }
        
        self.currentPage += 1
        
    LCAPiSubManager.request(.GetOvertimeApplyRecordHistory(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, pageIndex: self.currentPage, pageSize: 25, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
               
                
                guard  let resultDic : NSDictionary = jsonString["Result"] as? NSDictionary else{
                    return
                }
                guard  let resultArray : NSArray = resultDic["ApplyList"] as? NSArray else{
                    return
                }
                var salaryArray = [OvertimePlanModel].init()
                salaryArray = Mapper<OvertimePlanModel>().mapArray(JSONObject: resultArray)!
                if salaryArray.count <= 0 {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    return
                }
                self.historyArray += salaryArray
                self.tableView.reloadData()
                self.tableView.mj_footer.endRefreshing()
            }
        }
    }
    fileprivate func getOvertimeHistoryData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let demandBaseMigrantWorkerID = self.projectModel?.demandBaseMigrantWorkerID else{
            return
        }
        self.currentPage = 1
    LCAPiSubManager.request(.GetOvertimeApplyRecordHistory(demandBaseMigrantWorkerID: demandBaseMigrantWorkerID, pageIndex: 1, pageSize: 25, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                
                
                guard  let resultDic : NSDictionary = jsonString["Result"] as? NSDictionary else{
                    return
                }
                guard  let resultArray : NSArray = resultDic["ApplyList"] as? NSArray else{
                    return
                }
                if let totalList = resultDic["Total"] as? Int {
                    self.totalPage = (totalList/25)+1
                }
                self.historyArray = Mapper<OvertimePlanModel>().mapArray(JSONObject: resultArray)!
               
                self.tableView.reloadData()
            }
        }
    }
}

extension OvertimeRLViewController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.itemArray.count == 0 && self.historyArray.count == 0{
            self.tableView.isHidden = true
        }else{
            self.tableView.isHidden = false
        }
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
           return self.itemArray.count
        }
        return self.historyArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : OvertimeRecordCell = tableView.dequeueReusableCell(withIdentifier: "record") as! OvertimeRecordCell
        
        if indexPath.section == 0{
           cell.setCellDataWithModel(self.itemArray[indexPath.row])
        }
        if indexPath.section == 1{
            cell.setCellDataWithModel(self.historyArray[indexPath.row])
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.00001
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 && self.itemArray.count > 0{
        let view = UIView.init()
        let titleLabel = UILabel.init()
        titleLabel.frame = CGRect(x: 16, y: 10, width: 90, height: 19)
        titleLabel.font = wwFont_Medium(15)
        titleLabel.textColor = UIColor.init(white: 0.60, alpha: 1)
        view.addSubview(titleLabel)
        titleLabel.text = "加班计划"
        return view
        }
        if section == 1 && self.historyArray.count > 0{
            let view = UIView.init()
            let titleLabel = UILabel.init()
            titleLabel.frame = CGRect(x: 16, y: 10, width: 90, height: 19)
            titleLabel.font = wwFont_Medium(15)
            titleLabel.textColor = UIColor.init(white: 0.60, alpha: 1)
            view.addSubview(titleLabel)
            
            titleLabel.text = "加班历史"
            
            return view
        }
        let view = UIView.init()
        return view
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 && self.itemArray.count > 0 {
            return 39
        }
        if section == 1 && self.historyArray.count > 0{
            return 39
        }
        return 0.00001
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var selectModel:OvertimePlanModel?
        var selectDate:Date?
        
        if indexPath.section == 0{
           selectModel = self.itemArray[indexPath.row]
        }
        if indexPath.section == 1{
           selectModel = self.historyArray[indexPath.row]
        }
        
        if ((selectModel?.WorkDate) != nil) {
            selectDate = dateStringWithTToDate(dateString: (selectModel?.WorkDate)!)
        }
        let memorand = OvertimeMainViewController(nibName: "OvertimeMainViewController", bundle: nil)
        memorand.currentProject = self.projectModel
        memorand.selectDate = selectDate
        memorand.isCanApply = true
        memorand.title = "加班"
        memorand.isCalenlar = false
      self.navigationController?.pushViewController(memorand, animated: true)
    }
}





